package com.jgp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jgp.dto.DishDto;
import com.jgp.entity.Dish;
import com.jgp.entity.DishFlavor;
import com.jgp.entity.Employee;
import com.jgp.mapper.DishMapper;
import com.jgp.mapper.EmployeeMapper;
import com.jgp.service.DishFlavorService;
import com.jgp.service.DishService;
import com.jgp.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class Dishserviceimpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);

//        菜品id
        Long id = dishDto.getId();
        List<DishFlavor> flavors=dishDto.getFlavors();
        flavors=flavors.stream().map((item)->{
            item.setDishId(id);
            return item;
                }).collect(Collectors.toList());

//        保存菜品口味数据
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    @Override
    public DishDto getbyidWithFlavor(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto =new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }
    @Transactional
    @Override
    public void updatebyidWithFlavor(DishDto dishDto) {
       this.updateById(dishDto);
//       修改口味
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<DishFlavor> eq = lambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);
        Long id = dishDto.getId();
        List<DishFlavor> flavors=dishDto.getFlavors();
        flavors = flavors.stream().map((item)->{
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
//        保存菜品口味数据
        dishFlavorService.saveBatch( flavors);

    }
}
